// miniprogram/pages/xfz/xfz.js
// let tsc= require('./tsc.js')
// import util from '../../utils/util.js';
const wxbarcode = require('../../utils/xfz.js');
var util=require('../../utils/util')
import drawQrcode from '../../utils/weapp.qrcode.esm.js'
var toArrayBuffer = require('to-array-buffer');
var  Buffer  = require ('buffer/').Buffer
const PrinterJobs=require('../../printer/printerjobs')
const printerUtil = require('../../printer/printerutil')
const {myhicky}=require('../../utils/api')
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join(',')
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:[
    ], //设备集合
    id:'',
    inactive:[],
    parameter:'',   //假设参数
    isshow:false,
    state:true,
    code:'45678',
    inde:0,
    scr:'',
    num:1,
    value:'',
    status:1,
    data:{
    },
    radioItems: [
      {name: '面单', value: '1', checked: 'true'},
      {name: '小票', value: '0',}
    ],
  },
  //搜索蓝牙
  btn(){
    this.setData({
      list:[]
    })
    var that=this
    console.log(this.data.list,'查询')
    wx.startBluetoothDevicesDiscovery({
      success(res){
        //监听新设备
        wx.onBluetoothDeviceFound(function(res) {
          var devices = res.devices;
          if(devices[0].name!=''){
            // this.list.push(devices[0])
            var list=that.data.list
            list.push(devices[0])
            that.setData({
              list,
            })
          }
          // console.log('new device list has founded')
          // console.log(ab2hex(devices[0].advertisData))
        })
      },
      fail(res){
        console.log('搜索蓝牙失败',res)
      }
    })
  },
  //连接蓝牙
  connect(v){
    wx.showLoading({
        mask:true,
        title:'连接蓝牙中'
    })
    var that=this
    let {text} = v.currentTarget.dataset
    this.setData({
      id:text.deviceId
    })
    wx.createBLEConnection({
      deviceId:text.deviceId,
      timeout:9000,
      success(rse){
        console.log('连接蓝牙情况',rse)
        wx.getBLEDeviceServices({
          deviceId:text.deviceId,
          complete(rse){
            if(rse.errCode!=0){
              if(rse.errCode==10012){
                wx.showToast({
                  title: '连接蓝牙超时请重试',
                  icon: 'error',
                  duration: 1000
                })
              }else{
                wx.showToast({
                  title: '连接蓝牙异常',
                  icon: 'error',
                  duration: 1000
                })
              }
              return
            }
            //查询特征值
            that.setData({
              inactive:[]
            })
            for(var i in rse.services){
              wx.getBLEDeviceCharacteristics({
                deviceId:text.deviceId,
                serviceId:rse.services[i].uuid,
                complete(rse){
                  if(that.data.inactive[0]){
                    return
                  }
                  for(var j in rse.characteristics){
                    if(rse.characteristics[j].properties.write){
                          var arr=that.data.inactive
                          console.log(that.data.inactive,'查询值')
                          arr.push({
                            deviceId:rse.deviceId,
                            serviceId:rse.serviceId,
                            characteristicId:rse.characteristics[j].uuid,
                            name:text.name
                          })
                          wx.setStorageSync('bluetooth', v)
                          that.setData({
                            inactive:arr
                          })
                          wx.showToast({
                            title: '连接成功',
                            duration: 1000
                          })
                         that.speedUp(rse.deviceId)
                         break
                    }
                  }
                  if(!that.data.inactive[0]){
                    wx.showToast({
                      title: '获取蓝牙服务失败',
                      icon: 'error',
                      duration: 1000
                    })
                  }
                }
              })
            }
          }
        })
      },
      fail(rse){
        console.log('链接失败')
      },
      complete(){
        wx.stopBluetoothDevicesDiscovery({
          success(){
            console.log('停止搜索蓝牙')
          }
        })
      }
    })
    
  },
  //提速
  speedUp(id){
    wx.setBLEMTU({
      deviceId:id,
      mtu:510
    })
  },
  	//打印二维码
  printImgT(device, text,n) {//小票打印
    this.setData({
      inde:1
    })
    if(n==3){
      this.setData({
        state:false
      })
    }
    let tthis = this;
		const ctx = wx.createCanvasContext('canvas');
		ctx.clearRect(0, 0, 200, 200);
		drawQrcode({
			canvasId: 'canvas',
			text: String(text),
			width: 200,
			height: 200,
			callback(e) {
      // wxbarcode.barcode('barcode', tthis.data.code, 680, 160,function(){
				setTimeout(() => {
					// 获取图片数据
					wx.canvasGetImageData({
						canvasId: 'canvas',
						x: 0,
						y: 0,
						width: 200,
						height: 200,
						success(res) {
							let arr = tthis.convert4to2(res.data);
              let data = tthis.convert8to1(arr);                  //宽除8 //高本值
              const cmds = [].concat([27, 97,1], [29, 118, 48, 0, 25, 0, 200, 0], data, [27, 74, 3], [27, 64]);
							const buffer = toArrayBuffer(Buffer.from(cmds, 'gb2312'));
							let arrPrint = [];
							arrPrint.push(util.sendDirective([0x1B, 0x40]));
							// arrPrint.push(util.sendDirective([0x1B, 0x61, 0x01])); //居中
							for (let i = 0; i < buffer.byteLength; i = i + 20) {   //限制输入数据
								arrPrint.push(buffer.slice(i, i + 20));
							}
              // arrPrint.push(util.sendDirective([0x1B, 0x61, 0x01])); //居中
              if(n!=3){
                arrPrint.push(util.hexStringToBuff(`${tthis.data.parameter}\n`));
              }
							// arrPrint.push(util.hexStringToBuff("\n"));
              tthis.printInfo(device, arrPrint);
						}
					})
        }, 500);
      // }());
			}
		});
  },
  printImg() {
    let tthis = this;
    this.setData({
      state:true,
      inde:3
    })
    let stat=true
    wx.getImageInfo({
      src: 'http://zdht-it618jifen.oss-cn-beijing.aliyuncs.com/images/161932136004239.png',
      success: function (ret) {
        setTimeout(() => {
          var path = ret.path;
          var canvas = wx.createCanvasContext('shareCanvas')
          canvas.drawImage(path, 0, 0, 280, 100);
          canvas.draw()
          wx.canvasGetImageData({
            canvasId: 'shareCanvas',
            x: 0,
            y: 0,
            width: 280,
            height: 100,
            success(res) {
              let arr = tthis.convert4to1(res.data);
              let data = tthis.convert8to1(arr);
              const cmds = [].concat([27, 97, 1], [29, 118, 48, 0, 35, 0, 100, 0], data, [27, 74, 3], [27, 64]);
              const buffer = toArrayBuffer(Buffer.from(cmds, 'gb2312'));
              let arrPrint = [];
              arrPrint.push(util.sendDirective([0x1B, 0x40]));
              for (let i = 0; i < buffer.byteLength; i = i + 20) {
                arrPrint.push(buffer.slice(i, i + 20));
              }
              tthis.printInfo('xfz',arrPrint,stat,'3');
            },
            fail: function (error) {
              console.log("error:" + error);
            }
          })
        }, 200);
      },
    })
  },
  writeBLECharacteristicValue(n) {
    var num=this.data.num
    this.setData({
      num:num+1
    })
    let data=this.data.data
    let printerJobs = new PrinterJobs();
      if(n==1){
        printerJobs
        .print()
        .setAlign('LT')
        .print(printerUtil.fillLine())
        .setAlign('ct')
        .print('回单联')
        .setAlign('LT')
        .setLineSpacing(40)
        .print(data.storename?printerUtil.inline(`门店:${data.storename}`, `${this.time()}`):printerUtil.inline(`车牌号:xxxx`, `区域:xxxx`))
        .print(printerUtil.inline(`快递线路:${data.shipping_name}`,`会员ID:${data.uid}`))
        .print(printerUtil.inline(`寄件人:${data.jijianren}`, `电话:${data.jijianmobile}`))
        // .print(printerUtil.fillAround(`时间: ${this.time()}`))
      }else if(n==3){
        printerJobs
        // .setFont('A')
        .setLineSpacing(this.data.num==2?50:20)
        .setAlign('CT')
        .print(this.data.num==2?'客户联':'门店联')
        .setAlign('LT')
        .print()
        .print()
        .setLineSpacing(40)
        .print(printerUtil.inline('速购速递', `${data.date}`))
        .setSize(2,1)
        .print(`单 号:${this.data.parameter}`)
        .setSize(0,0)
        .print(printerUtil.inline(`付款方式:${data.pay_name}`,`费 用:${data.order_amount}`))
        .print(printerUtil.inline(`重 量:${data.weight}`,`操作人:${data.username}`))
        .setLineSpacing(this.data.num==2?60:10)
        .print(this.data.num==2?'':false)
        .print(this.data.num==2?printerUtil.fillLine():'')
      }
      else{
        printerJobs
        .setAlign('LT')
        .setFont('A')
        .print(printerUtil.inline('速购速递', `${this.time()}`))
        .print(printerUtil.fillLine())
        .setAlign('ct')
        .print('寄件联')
        .setAlign('LT')
        .setLineSpacing(40)
        .print(printerUtil.inline(`寄件人:${data.jijianren}`, `电话:${data.jijianmobile}`))
        .print(printerUtil.inline(`快递线路:${data.shipping_name}`,`会员ID:${data.uid}`))
        .print(printerUtil.inline(`收件人:${data.consignee}`, `电话:${data.mobile}`))
        // .print(printerUtil.fillAround(`时间: ${this.time()}`))
      }
    let buffer = printerJobs.buffer();
    console.log('ArrayBuffer', 'length: ' + buffer.byteLength, ' hex: ' + ab2hex(buffer));
    // 1.并行调用多次会存在写失败的可能性
    // 2.建议每次写入不超过20字节
    // 分包处理，延时调用
    const maxChunk = 20;
    const delay = 20;
    for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
      let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
      setTimeout(this._writeBLECharacteristicValue, j * delay, subPackage);
      // if(i+maxChunk>=length){
      //   let {deviceId}=this.data.inactive[0]
      //   if(n==1){
      //     this.setData({
      //       state:false
      //     })
      //     this.printImgT(deviceId, this.data.parameter);
      //     return
      //   }else if(n==3){
      //     if(this.data.num==3){
      //       this.setData({
      //         state:false
      //       })
      //       this.printImgT(deviceId, this.data.parameter,n);
      //       return
      //     }
      //     console.log('执行',length,i+maxChunk,i )
      //     setTimeout(() => {
      //       this.writeBLECharacteristicValue(3)
      //     },500);
      //     return
      //   }
      //   this.printImgT(deviceId, this.data.parameter);
      // }
    }

  },
  _writeBLECharacteristicValue(buffer) {
    let {deviceId,serviceId,characteristicId}=this.data.inactive[0]
    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      value: buffer,
      success(res) {
        console.log('writeBLECharacteristicValue success', res)
      },
      fail(res) {
        console.log('writeBLECharacteristicValue fail', res)
      }
    })
  },
  printInfo: function(device, arr, callback) {
    let tthis = this;
    if (arr.length > 0) {
      arr.shift();
      setTimeout(tthis.sendStr, 1,  arr[0]);
      tthis.printInfo(device, arr, callback);
    } else {
      // callback ? callback() : '';
      if(tthis.data.state){
        setTimeout(() => {
          // tthis.writeBLECharacteristicValue(tthis.data.inde)
        },1500);
      }else{
        wx.showToast({
          title: '打印完成',
          duration: 1000
        })
      }
    }
  },

  sendStr: function( bufferstr) {
    let {deviceId,serviceId,characteristicId}=this.data.inactive[0]
		let tthis = this;
		console.log('sendStr', bufferstr);
		wx.writeBLECharacteristicValue({
			deviceId: deviceId,
			serviceId: serviceId,
			characteristicId: characteristicId,
			value: bufferstr,
			success: function(res) {
				console.log('发送成功', res)
			},
			failed: function(res) {
				console.log("数据发送失败:" + JSON.stringify(res))
			},
			// complete: function(res) {
			// 	console.log("发送完成:" + JSON.stringify(res))
			// }
		})
	},
  print(){
    let {deviceId}=this.data.inactive[0]
    // wx.showLoading({
    //   mask:true,
    //   title:'打印中请稍等'
    // })
    this.printImgT(deviceId, this.data.parameter);
    // this.writeBLECharacteristicValue(0)
    console.log('执行完毕')
  },
  //小票
  receipt(){
    this.setData({
      num:1
    })
    let {deviceId}=this.data.inactive[0]
    this.printImg(deviceId);
    // this.writeBLECharacteristicValue(3)
  },
  //单选
  radioChange(e) {
    console.log('触发')
    const status = e.detail.value
    // for (let i = 0; i < this.data.radioItems.length; i++) {
    //   if (status.indexOf(this.data.radioItems[i].name) !== -1) {
    //     changed['radioItems[' + i + '].checked'] = true
    //   } else {
    //     changed['radioItems[' + i + '].checked'] = false
    //   }
    // }
    this.setData({
      status,
    })
  },
  //扫一扫
  scan(){
    var that=this
    wx.scanCode({
      success (res) {
        console.log(res.result)
        that.setData({
          value:res.result,
        })
        
        that.focus('dfz')
      }
    })
  },
  break(){
    let that=this
    let id=this.data.inactive[0].deviceId
    wx.closeBLEConnection({
      deviceId:id,
      success(rse){
        wx.showToast({
          title: '断开设备成功',
          icon: 'success',
          duration: 1000
        })
        that.setData({
          inactive:[]
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
   
  },
  time(){
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    //获取当前时间
    var n = timestamp * 1000;
    var date = new Date(n);
    //年
    var Y = date.getFullYear();
    //月
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    //时
    var h = date.getHours()<10?'0'+date.getHours():date.getHours();
    //分
    var m = date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes();
    //秒
    var s = date.getSeconds();
    return (Y+'/'+M+'/'+D+'/'+''+h+':'+m)
  },
  async focus(n){
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that=this
    if(that.data.parameter!=''){
      if(wx.getStorageSync('bluetooth')){
        console.log('自动连接')
        wx.getBluetoothAdapterState({
          success(res){
            if(res.available){
                that.connect(wx.getStorageSync('bluetooth'))
            }
          }
        })
      }else{
        wx.showToast({
          title: '请手动连接',
          icon: 'error',
          duration: 1000
        })
      }
    }
      wx.openBluetoothAdapter({
        success(res){
          wx.showToast({
            title: '初始化成功',
            icon: 'success',
            duration: 1000
          })
        },
        fail(sre){
          wx.showToast({
            title: '初始化失败',
            icon: 'error',
            duration: 1000
          })
        }
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var id=this.data.id
    wx.closeBLEConnection({
      deviceId:id,
      success(rse){
        console.log('断开设备成功')
        wx.closeBluetoothAdapter({
          success(){
            console.log('关闭蓝牙设备')
          }
        })
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  choose(){
    var that=this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        var src=res.tempFilePaths[0]
        console.log(src)
        that.setData({
          src,
        })
      }
    })
  },
  back(){
    let url=`https://www.baidu.com?id=2`
    wx.setStorageSync('url', url)
    wx.navigateTo({
      url: '/pages/skip/skip',
    })
  },
  	//4合1
    convert4to1(res) {
      let arr = [];
      for (let i = 0; i < res.length; i++) {
        if (i % 4 == 0) {
          let rule = 0.29900 * res[i] + 0.58700 * res[i + 1] + 0.11400 * res[i + 2];
          if (rule < 50) {
            res[i] = 0;
          } else {
            res[i] = 1;
          }
          arr.push(res[i]);
        }
      }
      return arr;
    },
    convert4to2(res) {
      let arr=[]
      for (let i = 0; i < res.length; i++) {
        if (i % 4 == 0) {
          let rule = 0.29900 * res[i] + 0.58700 * res[i + 1] + 0.11400 * res[i + 2];
            if (rule > 200) {
              res[i] = 0;
            } else {
              res[i] = 1;
            }
            arr.push(res[i]);
        }
      }
      return arr;
    },
    
    
    //8合1
    convert8to1(arr) {
      let data = [];
      for (let k = 0; k < arr.length; k += 8) {
        let temp = arr[k] * 128 + arr[k + 1] * 64 + arr[k + 2] * 32 + arr[k + 3] * 16 + arr[k + 4] * 8 + arr[k + 5] * 4 + arr[k + 6] * 2 + arr[k + 7] * 1
        data.push(temp);
      }
      return data;
    }
})